package org.example.demo1.servlets.functionPage;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import org.apache.ibatis.session.SqlSession;
import org.example.demo1.DAO.NovelDao;
import org.example.demo1.DAO.RolePermissionDao;
import org.example.demo1.DAO.UserRoleDao;
import org.example.demo1.DAO.CategoryDao;
import org.example.demo1.Entity.Novel;
import org.example.demo1.Entity.User;
import org.example.demo1.Entity.Category;
import org.example.demo1.utils.MybatisUtils;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.*;

@WebServlet("/API/Category")
public class CategoryServlet extends HttpServlet{
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 设置响应内容类型
        resp.setContentType("application/json;charset=UTF-8");
        PrintWriter out = resp.getWriter();
        
        try {
            // 查询数据库
            SqlSession sqlSession = MybatisUtils.getSqlSession();
            CategoryDao categoryDao = sqlSession.getMapper(CategoryDao.class);
            
            // 获取所有分类列表
            List<Category> categories = categoryDao.getCategoryList();
            
            // 构建响应数据
            Map<String, Object> result = new HashMap<>();
            result.put("code", 200);
            result.put("msg", "查询成功");
            result.put("total", categories.size());
            result.put("rows", categories);
            
            // 创建配置了序列化null值的Gson实例
            Gson gson = new GsonBuilder()
                    .serializeNulls()  // 这行配置会让Gson序列化null值
                    .create();
            
            // 返回JSON数据
            out.write(gson.toJson(result));
            
            // 关闭SqlSession
            sqlSession.close();
        } catch (Exception e) {
            // 处理异常
            Map<String, Object> result = new HashMap<>();
            result.put("code", 500);
            result.put("msg", "查询失败：" + e.getMessage());
            
            Gson gson = new Gson();
            out.write(gson.toJson(result));
            
            e.printStackTrace();
        } finally {
            out.close();
        }
    }
}
